package com.leenmvc.core.utils.collection;


import com.leenmvc.core.dao.mysql.MysqlBaseDaoImpl;
import com.leenmvc.core.utils.validator.ValidatorUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 树形结构工具类，如：菜单、部门等
 *
 * @author Mark HongJL,HuangZG
 * @since 1.0.0
 */
public class TreeUtils {

    /**
     * 根据pid，构建树节点
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid) {
        //pid不能为空
        ValidatorUtils.notNull("绘制树形集合的时候pid为空，请检查", pid);

        List<T> treeList = new ArrayList<>();
        for(T treeNode : treeNodes) {
            if (pid.equals(treeNode.getPid())) {
                treeList.add(findChildren(treeNodes, treeNode));
            }
        }
        return treeList;
    }

    /**
     * 查找子节点
     */
    private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) {
        for(T treeNode : treeNodes) {
            if(rootNode.getId().equals(treeNode.getPid())) {
                rootNode.getChildren().add(findChildren(treeNodes, treeNode));
            }
        }
        return rootNode;
    }

    /**
     * 构建树节点
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes) {
        List<T> result = new ArrayList<>();

        // list转map
        Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
        for(T treeNode : treeNodes){
            nodeMap.put(treeNode.getId(), treeNode);
        }

        for(T node : nodeMap.values()) {
            T parent = nodeMap.get(node.getPid());
            if(parent != null && !(node.getId().equals(parent.getId()))){
                parent.getChildren().add(node);
                continue;
            }
            result.add(node);
        }
        return result;
    }

    /**
     * 获取topid
     */
    public static <T extends TreeNode> Long findTopId(T t){
        T parent = null;
        //如果上级Id不等于空
        Long pid = t.getPid();
        if (pid == 0) {
            //自己就是顶级Id
            t.setTopId(0L);
            return 0L;
        } else {
            parent = MysqlBaseDaoImpl.getInstance().get(t.getClass(), t.getPid());
            //如果父实体的父Id不为空
            if (null != parent && 0 == parent.getPid()) {
                t.setTopId(parent.getId());
                return parent.getId();
            } else {
                return findTopId(parent);
            }
        }
    }

}
